package com.eclub.emotion.rootstone.server.context;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;


public class RsChannel {

	private Channel nettyChannel;
	private String remoteIP;
	private int remotePort;
	private String localIP;
	private int localPort;

	public RsChannel() {

	}

	public RsChannel(Channel nettyChannel) {
		super();
		this.nettyChannel = nettyChannel;
		SocketAddress remoteAddress = nettyChannel.getRemoteAddress();
		this.remoteIP = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress();
		this.remotePort = ((InetSocketAddress) remoteAddress).getPort();
		SocketAddress localAddress = nettyChannel.getLocalAddress();
		this.localIP = ((InetSocketAddress) localAddress).getAddress().getHostAddress();
		this.localPort = ((InetSocketAddress) localAddress).getPort();
	}

	public void close() {
		nettyChannel.close();
	}

	public void write(byte[] buffer) {
		if (buffer == null) {
			buffer = createErrorProtocol();
		}
		this.nettyChannel.write(ChannelBuffers.copiedBuffer(buffer, P_END_TAG));
	}

	public Channel getNettyChannel() {
		return nettyChannel;
	}

	public String getRemoteIP() {
		return remoteIP;
	}

	public int getRemotePort() {
		return remotePort;
	}

	public String getLocalIP() {
		return localIP;
	}

	public int getLocalPort() {
		return localPort;
	}

	public void setNettyChannel(Channel nettyChannel) {
		this.nettyChannel = nettyChannel;
	}

	public void setRemoteIP(String remoteIP) {
		this.remoteIP = remoteIP;
	}

	public void setRemotePort(int remotePort) {
		this.remotePort = remotePort;
	}

	public void setLocalIP(String localIP) {
		this.localIP = localIP;
	}

	public void setLocalPort(int localPort) {
		this.localPort = localPort;
	}

	private static final byte[] P_END_TAG = { 9, 11, 13, 17, 18 };

	public byte[] createErrorProtocol() {
		byte[] P_S_TAG = {};
		byte[] pByte = new byte[P_END_TAG.length + 1];
		System.arraycopy(P_S_TAG, 0, pByte, 0, 1);
		pByte[0] = 0;
		System.arraycopy(P_END_TAG, 0, pByte, P_END_TAG.length + 1, P_END_TAG.length);
		return pByte;
	}
}
